﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace StudentManagement.Models
{
    public class SqlStudentRepository : IStudentRepository
    {

        private readonly AppDBContext _context;
        private readonly ILogger<SqlStudentRepository> _logger;

        public SqlStudentRepository(AppDBContext context,ILogger<SqlStudentRepository> logger)
        {
            _context = context;
            _logger = logger;
        }

        public Student Add(Student student)
        {
            _context.Student.Add(student);
            _context.SaveChanges();
            return student;
        }

        public Student Delete(int id)
        {
            Student student=_context.Student.Find(id);

            if (student!=null)
            {
                _context.Student.Remove(student);
                _context.SaveChanges();
            }

            return student;
        }

        public IEnumerable<Student> GetAllStudents()
        {
            _logger.LogTrace("Trace(跟踪) Log");
            _logger.LogDebug("Debug(调试) Log");
            _logger.LogInformation("信息(Information) Log");
            _logger.LogWarning("警告(Warning) Log");
            _logger.LogError("错误(Error) Log");
            _logger.LogCritical("严重(Criticl) Log");

            return _context.Student;
        }

        public Student GetStudent(int id)
        {
            return _context.Student.Find(id);
        }

        public void Save(Student student)
        {
            throw new NotImplementedException();
        }

        public Student Update(Student updateStudent)
        {
            var student=_context.Student.Attach(updateStudent);

            student.State = EntityState.Modified;

            _context.SaveChanges();

            return updateStudent;
        }
    }
}
